<template>
  <div class="crime-prediction-chart">
    <div class="chart-header">
      <h3>犯罪预测（承载能力预测）</h3>
      <div class="chart-status">
        <div class="status-indicator" :class="predictionStatus">
          <div class="pulse-dot"></div>
          <span>{{ predictionStatusText }}</span>
        </div>
      </div>
    </div>

    <div class="chart-container">
      <div id="crime-prediction-chart" class="prediction-chart"></div>
    </div>

  </div>
</template>

<script>
import { Chart } from '@antv/g2'

export default {
  name: 'CrimePredictionChart',
  data() {
    return {
      predictionChart: null,
      predictionData: [],
      currentPredictionPeak: 0,
      currentCapacityLimit: 3000,
      updateTimer: null
    }
  },
  computed: {
    predictionPeak() {
      return this.currentPredictionPeak.toFixed(1) + '%'
    },
    capacityLimit() {
      return '100%'
    },
    remainingCapacity() {
      const remaining = 100 - this.currentPredictionPeak
      const sign = remaining >= 0 ? '' : ''
      return remaining.toFixed(1) + '%'
    },
    remainingCapacityClass() {
      // 当承载率超过100%时，显示负数（超载）
      if (this.currentPredictionPeak > 100) return 'critical'
      const remainingPercent = 100 - this.currentPredictionPeak
      if (remainingPercent < 5) return 'critical'
      if (remainingPercent < 10) return 'warning'
      if (remainingPercent < 20) return 'caution'
      return 'normal'
    },
    predictionStatus() {
      if (this.currentPredictionPeak > 105) return 'critical'
      if (this.currentPredictionPeak > 95) return 'warning'
      if (this.currentPredictionPeak > 85) return 'caution'
      return 'normal'
    },
    predictionStatusText() {
      const status = this.predictionStatus
      switch (status) {
        case 'critical': return '严重超载'
        case 'warning': return '接近上限'
        case 'caution': return '需关注'
        default: return '正常'
      }
    }
  },
  mounted() {
    this.initializeChart()
    // this.startDataUpdate()
  },
  beforeDestroy() {
    if (this.updateTimer) {
      clearInterval(this.updateTimer)
    }
    if (this.predictionChart) {
      this.predictionChart.destroy()
    }
  },
  methods: {
    initializeChart() {
      this.$nextTick(() => {
        this.initPredictionChart()
      })
    },

    initPredictionChart() {
      const container = document.getElementById('crime-prediction-chart')
      if (!container) return

      this.predictionChart = new Chart({
        container: 'crime-prediction-chart',
        autoFit: true,
        height: 250,
        theme: 'dark'
      })

      // 生成预测数据
      this.generatePredictionData()

      this.predictionChart.axis('x', {
        title: false
      })

      this.predictionChart.axis('y', {
        title: false
      })

      // 完整的承载率趋势线（历史+预测）
      this.predictionChart
        .line()
        .data(this.predictionData)
        .encode('x', 'year')
        .encode('y', 'capacityRate')
        .scale('y', { domain: [0, 120], nice: true })
        .style('stroke', '#00ffff')
        .style('strokeWidth', 2)
        .animate('enter', { type: 'waveIn', duration: 1000 })

      // 添加预测数据开始的分隔线
      const predictionStartIndex = this.predictionData.findIndex(d => d.isPrediction)
      if (predictionStartIndex > 0) {
        const predictionStartPoint = this.predictionData[predictionStartIndex]
        this.predictionChart
          .point()
          .data([predictionStartPoint])
          .encode('x', 'year')
          .encode('y', 'capacityRate')
          .style('fill', '#00ffff')
          .style('stroke', '#ffffff')
          .style('strokeWidth', 2)
          .style('r', 6)
          .tooltip({ title: '预测数据起始点' })
      }

      // 添加承载率阈值线（80%）
      const thresholdData = this.predictionData.map(d => ({ year: d.year, capacityRate: 80 }))
      this.predictionChart
        .line()
        .data(thresholdData)
        .encode('x', 'year')
        .encode('y', 'capacityRate')
        .style('stroke', '#ffa500')
        .style('strokeWidth', 1)
        .style('strokeDasharray', [3, 3])
        .tooltip({ title: '承载率预警线: 80%' })

      // 添加承载率上限线（100%）
      const limitData = this.predictionData.map(d => ({ year: d.year, capacityRate: 100 }))
      this.predictionChart
        .line()
        .data(limitData)
        .encode('x', 'year')
        .encode('y', 'capacityRate')
        .style('stroke', '#ff4444')
        .style('strokeWidth', 1)
        .style('strokeDasharray', [5, 5])
        .tooltip({ title: '承载率上限: 100%' })

      // 添加区域填充（仅历史数据）
      this.predictionChart
        .area()
        .data(this.predictionData.filter(d => !d.isPrediction))
        .encode('x', 'year')
        .encode('y', 'capacityRate')
        .scale('y', { domain: [0, 120], nice: true })
        .style('fill', 'linear-gradient(180deg, rgba(0, 255, 255, 0.2) 0%, rgba(0, 255, 255, 0.05) 100%)')
        .tooltip(false)

      this.predictionChart.render()
    },

    generatePredictionData() {
      this.predictionData = []
      const currentYear = new Date().getFullYear()

      // 生成过去3年的历史数据 + 未来3年的预测数据
      for (let yearOffset = -2; yearOffset <= 2; yearOffset++) {
        const year = currentYear + yearOffset
        const yearLabel = `${year}年`
        const isPrediction = yearOffset > 0 // 未来年份为预测数据

        // 生成年度承载率数据（0-100%）
        let baseRate = 0

        if (isPrediction) {
          // 预测数据：基于历史趋势继续增长，确保与历史数据连续
          const lastHistoricalRate = 35 + 2 * 12 // yearOffset = 0时的历史数据基准值
          baseRate = lastHistoricalRate + yearOffset * 8 // 从历史数据末尾开始继续增长
        } else {
          // 历史数据：从2022年开始逐渐增长
          const historicalYearOffset = year - (currentYear - 2)
          baseRate = 35 + historicalYearOffset * 12
        }

        // 添加随机波动
        const randomFactor = (Math.random() - 0.5) * 15 // ±7.5%的随机波动
        let capacityRate = baseRate + randomFactor

        // 允许超过100%，但设置合理的上限
        capacityRate = Math.max(15, Math.min(115, capacityRate))

        this.predictionData.push({
          year: yearLabel,
          capacityRate: Math.round(capacityRate * 10) / 10, // 保留一位小数
          isPrediction,
          yearValue: year
        })
      }

      // 更新当前峰值承载率
      this.currentPredictionPeak = Math.max(...this.predictionData.map(d => d.capacityRate))
    },

    startDataUpdate() {
      this.updateTimer = setInterval(() => {
        this.updatePredictionData()
      }, 5000) // 每5秒更新一次
    },

    updatePredictionData() {
      if (!this.predictionChart) return

      this.generatePredictionData()

      // 更新图表数据
      this.predictionChart.changeData(this.predictionData)

      // 强制重新渲染
      this.predictionChart.render()
    }
  }
}
</script>

<style scoped>
.crime-prediction-chart {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 15px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 0 15px;
}

.chart-header h3 {
  margin: 0;
  color: #00ffff;
  font-size: 16px;
  font-weight: 600;
  text-shadow: 0 0 10px rgba(0, 255, 255, 0.5);
}

.chart-status {
  display: flex;
  align-items: center;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-indicator.normal {
  background: rgba(0, 255, 136, 0.2);
  border: 1px solid rgba(0, 255, 136, 0.3);
  color: #00ff88;
}

.status-indicator.caution {
  background: rgba(255, 255, 0, 0.2);
  border: 1px solid rgba(255, 255, 0, 0.3);
  color: #ffff00;
}

.status-indicator.warning {
  background: rgba(255, 165, 0, 0.2);
  border: 1px solid rgba(255, 165, 0, 0.3);
  color: #ffa500;
}

.status-indicator.critical {
  background: rgba(255, 68, 68, 0.2);
  border: 1px solid rgba(255, 68, 68, 0.3);
  color: #ff4444;
}

.pulse-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  animation: pulse 2s ease-in-out infinite;
}

.status-indicator.normal .pulse-dot { background: #00ff88; }
.status-indicator.caution .pulse-dot { background: #ffff00; }
.status-indicator.warning .pulse-dot { background: #ffa500; }
.status-indicator.critical .pulse-dot { background: #ff4444; }

@keyframes pulse {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.5;
    transform: scale(1.2);
  }
}

.chart-container {
  flex: 1;
  margin-bottom: 15px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  border: 1px solid rgba(0, 255, 255, 0.1);
  overflow: hidden;
}

.prediction-chart {
  width: 100%;
  height: 100%;
}

.capacity-summary {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 12px 15px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 6px;
  margin: 0 15px;
}

.summary-item {
  text-align: center;
}

.summary-item .label {
  display: block;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 4px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.summary-item .value {
  display: block;
  font-size: 16px;
  font-weight: 700;
  color: #00ffff;
  text-shadow: 0 0 8px rgba(0, 255, 255, 0.5);
}

.summary-item .value.critical {
  color: #ff4444;
  text-shadow: 0 0 8px rgba(255, 68, 68, 0.5);
}

.summary-item .value.warning {
  color: #ffa500;
  text-shadow: 0 0 8px rgba(255, 165, 0, 0.5);
}

.summary-item .value.caution {
  color: #ffff00;
  text-shadow: 0 0 8px rgba(255, 255, 0, 0.5);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chart-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .capacity-summary {
    flex-direction: column;
    gap: 10px;
  }

  .summary-item {
    width: 100%;
  }

  .summary-item .value {
    font-size: 14px;
  }
}
</style>
